<template>
    <div style="margin-top: 5px" class="unselectable">
        <div class="flex-container">
            <div class="header">
                <p class="title">{{ clueData.name }} / {{ clueData.clueId }}</p>
                <hr />
                <div style="margin-left: 20px; margin-top: 10px; height: 300px">
                    <el-descriptions :label-style="italicLabelStyle" :column="3">
                        <el-descriptions-item label="线索创建时间"
                            ><p>{{ formatDateTime(clueData.createTime) }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="客户手机号码"
                            ><p>{{ clueData.phone }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="渠道来源"
                            ><p>{{ clueData.channelName }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="线索分配者"
                            ><p>{{ clueData.allocator }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="线索归属时间"
                            ><p>{{ formatDateTime(clueData.belongTime) }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="线索归属人"
                            ><p>{{ clueData.owner }}</p></el-descriptions-item
                        >
                        <el-descriptions-item label="所属促销活动信息"
                            ><p>
                                {{ clueData.activityName }} / {{ clueData.activityInfo }}
                            </p></el-descriptions-item
                        >
                        <el-descriptions-item></el-descriptions-item>
                        <el-descriptions-item label="" span="2">
                            <div class="button-container">
                                <el-button
                                    type="danger"
                                    class="mr-2"
                                    :disabled="isDisabled"
                                    @click="openInvalidDialog"
                                    >无效线索</el-button
                                >
                                <el-button type="primary" :disabled="isDisabled" @click="convertToBusiness"
                                    >转为商机</el-button
                                >
                            </div>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
            </div>

            <div class="tit">
                <p>线索跟进记录</p>
                <hr />
                <el-descriptions :label-style="italicLabelStyle" :column="1">
                    <el-descriptions-item
                        v-for="record in followUpRecords"
                        :key="record.recordId"
                        :label="`${record.createBy}：${record.info || ''}`"
                    >
                        <p>{{ formatDateTime(record.createTime) }}</p>
                    </el-descriptions-item>
                </el-descriptions>
            </div>
        </div>
        <div class="containerTwo" style="margin-top: 20px; margin-bottom: 20px">
            <div class="header">
                <p class="title">线索跟进</p>
                <hr />
                <div style="margin-left: 20px; margin-top: 20px">
                    <el-descriptions :label-style="italicLabelStyle" :column="3">
                        <el-descriptions-item label="客户姓名"
                            ><br /><el-input
                                v-model="clueData.name"
                                style="width: 365px"
                                :disabled="isDisabled"
                        /></el-descriptions-item>
                        <el-descriptions-item label="性别"
                            ><br />
                            <el-select v-model="clueData.gender" placeholder="请选择" :disabled="isDisabled">
                                <el-option
                                    v-for="item in genderOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                /> </el-select
                        ></el-descriptions-item>
                        <el-descriptions-item label="年龄"
                            ><br /><el-input-number v-model="clueData.age" :min="1" :disabled="isDisabled"
                        /></el-descriptions-item>
                        <el-descriptions-item label="客户微信号码"
                            ><br /><el-input
                                v-model="clueData.weixin"
                                style="width: 365px"
                                :disabled="isDisabled"
                        /></el-descriptions-item>
                        <el-descriptions-item label="客户QQ号码"
                            ><br /><el-input
                                v-model="clueData.qq"
                                style="width: 365px"
                                :disabled="isDisabled"
                        /></el-descriptions-item>
                        <el-descriptions-item label="客户手机号码"
                            ><br /><el-input
                                v-model="clueData.phone"
                                style="width: 365px"
                                :disabled="isDisabled"
                        /></el-descriptions-item>
                    </el-descriptions>
                    <el-descriptions :column="1">
                        <el-descriptions-item label="客户意向等级"
                            ><br />
                            <el-radio-group v-model="clueData.level" :disabled="isDisabled">
                                <el-radio :label="1" size="large">近期报名</el-radio>
                                <el-radio :label="2" size="large">打算报名，考虑中</el-radio>
                                <el-radio :label="3" size="large">了解一下</el-radio>
                                <el-radio :label="4" size="large">打酱油</el-radio>
                            </el-radio-group>
                        </el-descriptions-item>
                        <el-descriptions-item label="客户意向类型"
                            ><br />
                            <el-radio-group v-model="clueData.subject" :disabled="isDisabled">
                                <el-radio :label="1" size="large">舞蹈类</el-radio>
                                <el-radio :label="2" size="large">游泳类</el-radio>
                                <el-radio :label="3" size="large">拳击类</el-radio>
                            </el-radio-group>
                        </el-descriptions-item>
                        <el-descriptions-item label="跟进记录">
                            <el-input
                                v-model="textarea"
                                type="textarea"
                                placeholder="请输入内容"
                                :rows="5"
                                :disabled="isDisabled"
                            />
                        </el-descriptions-item>
                        <el-descriptions-item label="下次跟进时间"
                            ><br />
                            <el-date-picker
                                v-model="clueData.nextTime"
                                type="datetime"
                                placeholder="选择日期时间"
                                :disabled="isDisabled"
                            >
                            </el-date-picker>
                        </el-descriptions-item>
                        <el-descriptions-item align="right">
                            <el-button type="primary" :disabled="isDisabled" @click="submitFollowUp"
                                >提交</el-button
                            >
                            <el-button style="margin-right: 15px" :disabled="isDisabled" @click="goBack"
                                >返回</el-button
                            >
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
            </div>
        </div>
        <!-- 无效线索对话框 -->
        <el-dialog v-model="invalidDialogVisible" title="无效线索" style="width: 500px; height: 400px" left>
            <el-form ref="invalidFormRef" :model="invalidForm" :rules="invalidRules" label-width="80px">
                <el-form-item label="原因" prop="record">
                    <el-select v-model="invalidForm.record" placeholder="请选择原因" style="width: 100%">
                        <el-option label="空号" value="空号"></el-option>
                        <el-option label="停机" value="停机"></el-option>
                        <el-option label="无法联系" value="无法联系"></el-option>
                        <el-option label="其他" value="其他"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark" style="margin-top: 40px">
                    <el-input
                        v-model="invalidForm.remark"
                        type="textarea"
                        placeholder="请输入备注信息"
                        :rows="5"
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="invalidDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitInvalidForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getClueT, getClueTwo, addInvalid, addBusiness, addFollow } from '@/api/clue/clue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const textarea = ref('');
const route = useRoute();
const clueData = ref({});
const followUpRecords = ref([]);
const isDisabled = ref(false);

const genderOptions = [
    { value: 0, label: '女' },
    { value: 1, label: '男' },
    { value: 2, label: '未知' },
];

const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '';
    return dateTime.replace('T', ' ');
};

onMounted(() => {
    const clueId = Number(route.params.clueId);
    console.log('获取的clueId:', clueId);

    if (clueId) {
        getClueT(clueId)
            .then(res => {
                console.log('接口返回数据:', res);
                if (res.code === 200) {
                    clueData.value = res.data;
                    console.log('赋值后的clueData:', clueData.value);
                }
            })
            .catch(error => {
                console.error('获取线索详细信息失败:', error);
            });

        getClueTwo(clueId)
            .then(res => {
                console.log('跟进记录接口返回数据:', res);
                if (res.code === 200) {
                    followUpRecords.value = res.data;
                    console.log('赋值后的跟进记录:', followUpRecords.value);
                }
            })
            .catch(error => {
                console.error('获取跟进记录信息失败:', error);
            });
    }
});

const italicLabelStyle = {
    fontStyle: 'italic',
};

// 无效线索对话框
const invalidDialogVisible = ref(false);
const invalidForm = ref({
    record: '',
    remark: '',
});
const invalidFormRef = ref(null);
const invalidRules = {
    record: [{ required: true, message: '请选择无效原因', trigger: 'change' }],
};

// 打开无效线索对话框
const openInvalidDialog = () => {
    invalidDialogVisible.value = true;
};

// 提交无效线索表单
const submitInvalidForm = async () => {
    if (invalidFormRef.value) {
        await invalidFormRef.value.validate((valid, fields) => {
            if (valid) {
                
                let combinedRecord = invalidForm.value.record;
                if (invalidForm.value.remark) {
                    combinedRecord += `：${invalidForm.value.remark}`;
                }
                
                const data = {
                    clueId: route.params.clueId,
                    record: combinedRecord 
                };
                
                addInvalid(data)
                    .then(res => {
                        if (res.code === 200) {
                            ElMessage.success('无效线索成功');
                            invalidDialogVisible.value = false;

                            // 重新获取跟进记录
                            const clueId = Number(route.params.clueId);
                            getClueTwo(clueId)
                                .then(res => {
                                    console.log('重新获取的跟进记录接口返回数据:', res);
                                    if (res.code === 200) {
                                        followUpRecords.value = res.data;
                                        console.log('重新赋值后的跟进记录:', followUpRecords.value);
                                    }
                                })
                                .catch(error => {
                                    console.error('重新获取跟进记录信息失败:', error);
                                });

                            // 跳转到线索管理首页并刷新数据
                            router.push('/clue/index')
                        } else {
                            ElMessage.error('标记无效线索失败');
                        }
                    })
                    .catch(error => {
                        console.error('标记无效线索失败:', error);
                        ElMessage.error('标记无效线索失败');
                    });
            } else {
                console.log('error submit!', fields);
            }
        });
    }
};

// 转为商机
const convertToBusiness = () => {
    const clueId = Number(route.params.clueId);
    ElMessageBox.confirm('是否将当前线索转为客户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            addBusiness(clueId)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('线索转为商机成功');

                        // 跳转首页并刷新数据
                        router.push('/clue/index')
                    } else {
                        ElMessage.error('线索转为商机失败');
                    }
                })
                .catch(error => {
                    console.error('线索转为商机失败:', error);
                    ElMessage.error('线索转为商机失败');
                });
        })
        .catch(() => {
            ElMessage.info('已取消转换');
        });
};

// 提交跟进记录
const submitFollowUp = async () => {
    const clueId = Number(route.params.clueId);
    const followUpData = {
        clueId,
        record: textarea.value,
        name: clueData.value.name,
        gender: clueData.value.gender,
        age: clueData.value.age,
        weixin: clueData.value.weixin,
        qq: clueData.value.qq,
        phone: clueData.value.phone,
        level: clueData.value.level,
        subject: clueData.value.subject,
        nextTime: clueData.value.nextTime
    };

    try {
        const res = await addFollow(followUpData);
        if (res.code === 200) {
            ElMessage.success('线索跟进记录提交成功');
            
            // 提交成功后跳转到线索列表页
            router.push('/clue/index')
        } else {
            ElMessage.error('线索跟进记录提交失败');
        }
    } catch (error) {
        console.error('线索跟进记录提交失败:', error);
        ElMessage.error('线索跟进记录提交失败');
    }
};

// 添加返回方法
const goBack = () => {
    router.push('/clue/index');
};
</script>

<style lang="scss" scoped>

:deep .containerTwo {
    width: 100% !important;
}

.flex-container {
    position: relative;
    display: flex;
    gap: 20px;
    width: 100%;
    box-sizing: border-box;
}

.header {
    width: 73%;
    box-shadow: var(--el-box-shadow-light);
    margin-top: 10px;
    padding-bottom: 20px;
    .title {
        height: 43px;
        width: 100%;
        padding: 14px 15px 7px !important;
        min-height: 40px;
    }
}

.tit {
    position: absolute;
    right: 0;
    top: 0;
    width: 25%;
    box-shadow: var(--el-box-shadow-light);
    margin-top: 10px;
    padding: 15px;
    height: auto;
    z-index: 1; 
    p {
        font-size: 16px;
        margin-bottom: 5px;
    }
}

.record-container {
    max-height: 220px;
    overflow-y: auto;
}

.record-item {
    border-bottom: 1px solid #eee;
    padding: 10px 0;

    .record-date {
        font-weight: bold;
        color: #606266;
    }

    .record-content {
        margin-top: 5px;
        color: #303133;
    }
}

:deep .el-descriptions__body .el-descriptions__table:not(.is-bordered) .el-descriptions__cell {
    padding-bottom: 20px;
}
:deep .el-descriptions__label {
    font-style: italic;
    font-weight: bold;
    font-size: 16px;
}
:deep .el-descriptions {
    p {
        font-size: 16px;
    }
}

.button-container {
    display: flex;
    gap: 8px;
    padding-top: 4px;
}
.mr-2 {
    margin-right: 8px;
}
</style>